<?php

/*
  Contain the common functions
  required in shop and admin pages
 */
require_once 'config.php';
require_once 'db-funct.php';
include('ResizeClassImage_helper.php');

function setSession($sessionName = array()) {
    if (is_array($sessionName)) {
        foreach ($sessionName as $keyValue => $value) {
            $_SESSION[$keyValue] = $value;
        }
    }
}

function clearSession($sessionName = array()) {

    if (is_array($sessionName)) {
        foreach ($sessionName as $keyValue) {
            unset($_SESSION[$keyValue]);
        }
    }
}

date_default_timezone_set('Asia/Bangkok');

//for current url
$CURRENT_URL = (!empty($_SERVER['HTTPS'])) ? "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
/*
  Make sure each key name in $requiredField exist
  in $_POST and the value is not empty
 */

function getCartContent() {
    $cartContent = array();
    $session_id = session_id();
    $sql = "SELECT ct.ct_id, ct.pd_id, ct.ct_qty, pd.product_name, ph.product_id, ph.price,thumbnail,pd.owner, phar.pharmacy_id FROM tblproduct_in_pharmacy AS ph " .
            "INNER JOIN tbl_cart AS ct ON ph.pid = ct.pd_id " .
            "INNER JOIN tblproduct AS pd ON ph.product_id = pd.id " .
            "INNER JOIN tblimage AS img ON img.product_id = pd.id " .
            "INNER JOIN tblpharmacy AS phar ON phar.user_id = pd.owner " .
            "WHERE ct.ct_session_id = '$session_id'";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_assoc($result)) {
        $cartContent[] = $row;
    }
    return $cartContent;
}

/*
  Detect has record in a table
 */

function getProvinceName($province_id) {
    $name = "";
    $sql = "SELECT province_name FROM tblprovince WHERE province_id = $province_id";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        $row = mysql_fetch_assoc($result);
        $name = $row['province_name'];
        return $name;
    }
}

function CountReceivePre($userId) {
    $num = '';
    $sql = "SELECT COUNT(o.ordernance_id) AS order_id FROM tblordernance AS o, tblordernance_in_pharmacy AS oip WHERE o.user_id = $userId AND oip.ordernance_id = o.ordernance_id AND oip.pharma_check = 1 AND oip.user_check = 0";
    $result = mysql_query($sql);
    $row = mysql_fetch_assoc($result);
    if ($row['order_id'] > 0) {
        $num = '<strong style="color:red">(' . $row['order_id'] . ')</strong>';
    } else {
        $num = '';
    }
    return $num;
}

function CountPharmaPre($pharmaId) {
    $num = '';
    $sql = "SELECT COUNT(ordernance_id) AS order_id FROM tblordernance_in_pharmacy WHERE pharmacy_id = $pharmaId AND pharma_check = 0";
    $result = mysql_query($sql);
    $row = mysql_fetch_assoc($result);
    if ($row['order_id'] > 0) {
        $num = '<strong style="color:red">(' . $row['order_id'] . ')</strong>';
    } else {
        $num = '';
    }
    return $num;
}

function updatePreStatus($orderId, $pharId) {
    $sql = "UPDATE tblordernance_in_pharmacy SET user_check = 1 WHERE ordernance_id = $orderId AND pharmacy_id = $pharId";
    return mysql_query($sql);
}

function uploadProductimage($newimage, $resizeWidth, $resizeHeight = null, $logoPath, $logoPosition) {
    $tempdir = S_ROOT . '/product/images/';
    $tempdir_thumb = S_ROOT . '/product/images/thumb/';
    if (!file_exists($tempdir_thumb)) {
        mkdir($tempdir_thumb, 0777, true);
    }
//        applyWaterMark($imagePath, $origin_img);

    /* upload with resize and watermark */
    $names = $newimage['name'];
    $temp = explode(".", $names);
    $names = genRandomString(10) . '.' . end($temp);
    $names = Special_String_Upload($names);
    if (!file_exists($tempdir . $names)) {
        $name = $names;
    } else {
        $name = genRandomString(10) . '-' . $names;
    }
    $supported_image = array(
        'gif',
        'jpg',
        'jpeg',
        'png'
    );

    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (in_array($ext, $supported_image)) {
        $updouad = uploadImg($newimage, $tempdir, $name);
        if ($updouad) {
            copy($tempdir . $name, $tempdir_thumb = $tempdir_thumb . $name);
            $isUpload = TRUE;

            /* resize */
            if ($resizeWidth > 0) {
                \ChipVN\Image::resize($tempdir_thumb, 250, 200, 'adaptive');
            }
        }
        /* watermark */
        if ($logoPath) {
            /* water mark text */
            //applyWaterMark($tempdir, $name);
            /* water mark logo */
            \ChipVN\Image::watermark($tempdir . $name, $logoPath, $logoPosition);
        }
    }

    /* end upload with resize and watermark */

    return $name;
}

function uploadImg($FILES, $tempdir_thumb, $name = '') {
    return move_uploaded_file($FILES['tmp_name'], $tempdir_thumb . $name);
}

function getTotalPrice($orderId, $pharId) {
    $price = '';
    $sql = "SELECT total_price FROM tblordernance_in_pharmacy WHERE ordernance_id = $orderId AND pharmacy_id = $pharId";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        $row = mysql_fetch_assoc($result);
        $price = $row['total_price'];
        return $price;
    }
}

function getPharmaName($id) {
    $name = "";
    $sql = "SELECT pharmacy_name FROM tblpharmacy WHERE user_id = $id";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        $row = mysql_fetch_assoc($result);
        $name = $row['pharmacy_name'];
        return $name;
    }
}

function getProductName($id) {
    $name = '';
    $sql = "SELECT product_name FROM tblproduct WHERE id = $id";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        $row = mysql_fetch_assoc($result);
        $name = $row['product_name'];
        return $name;
    }
}

function getUserName($id) {
    $name = '';
    $sql = "SELECT * FROM tbluser WHERE id = $id";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        $row = mysql_fetch_assoc($result);
        $first_name = $row['first_name'];
        $last_name = $row['last_name'];
        $name = $first_name . ' ' . $last_name;
        return $name;
    }
}

function getCountryName($id) {
    $name = '';
    $sql = "SELECT country_name FROM tblcountries WHERE id = $id";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        $row = mysql_fetch_assoc($result);
        $name = $row['country_name'];
        return $name;
    }
}

function getCategoryName($id) {
    if (!empty($id)) {
        $name = '';
        $sql = "SELECT category_name FROM tblcategory WHERE id = $id";
        $result = mysql_query($sql);
        if (dbNumRows($result)) {
            $row = mysql_fetch_assoc($result);
            $name = $row['category_name'];
            return $name;
        }
    }
}

function existRecord($tblName, $condition) {
    // Get the information from database
    $sql = "SELECT *
	FROM $tblName
	WHERE $condition";

    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        return true;
    } else
        return false;
}

/**
 * Replaces &amp; with & for xhtml compliance
 *
 * Needed to handle unicode conflicts due to unicode conflicts
 */
function ampReplace($text) {
    $text = str_replace('&&', '*--*', $text);
    $text = str_replace('&#', '*-*', $text);
    $text = str_replace('&amp;', '&', $text);
    $text = preg_replace('|&(?![\w]+;)|', '&amp;', $text);
    $text = str_replace('*-*', '&#', $text);
    $text = str_replace('*--*', '&&', $text);

    return $text;
}

/*
  Function to Format the id value
 */

//State image function, item id, state value, querystring, current user (use for manage user account only)
function stateImage($id, $state, $strLink = "", $currentItem = false) {
    $img = '<img src="' . W_ROOT . '/images/publish_x.png" alt="Disabled" title="Disabled" border="0" />';

    if ($currentItem)
        $img = '<img src="' . W_ROOT . '/images/tick.png" alt="Enabled" title="Enabled" border="0" />';
    else {
        if ($state == 0) {
            $img = '<a href="' . $_SERVER['PHP_SELF'] . '?' . htmlspecialchars(getAllGetParams(array('view', 'id', 'front'))) . '&amp;view=publish&amp;publish=1&amp;id=' . $id . '"><img src="' . W_ROOT . '/images/publish_x.png" alt="Enabled" title="Enabled" border="0" /></a>';
        } else {
            $img = '<a href="' . $_SERVER['PHP_SELF'] . '?' . htmlspecialchars(getAllGetParams(array('view', 'id', 'front'))) . '&amp;view=publish&amp;publish=0&amp;id=' . $id . '"><img src="' . W_ROOT . '/images/tick.png" alt="Disabled" title="Disabled" border="0" /></a>';
        }
    }
    return $img;
}

function stateProduct($pro_id, $phar_id, $state, $strLink = "", $currentItem = false) {
    $img = '<img src="' . W_ROOT . '/images/publish_x.png" alt="Disabled" title="Disabled" border="0" />';

    if ($currentItem)
        $img = '<img src="' . W_ROOT . '/images/tick.png" alt="Enabled" title="Enabled" border="0" />';
    else {
        if ($state == 0) {
            $img = '<a href="' . $_SERVER['PHP_SELF'] . '?' . htmlspecialchars(getAllGetParams(array('view', 'id', 'front'))) . '&amp;view=publish&amp;publish=1&amp;id=' . $pro_id . '&amp;pharm_id=' . $phar_id . '"><img src="' . W_ROOT . '/images/publish_x.png" alt="Enabled" title="Enabled" border="0" /></a>';
        } else {
            $img = '<a href="' . $_SERVER['PHP_SELF'] . '?' . htmlspecialchars(getAllGetParams(array('view', 'id', 'front'))) . '&amp;view=publish&amp;publish=0&amp;id=' . $pro_id . '&amp;pharm_id=' . $phar_id . '"><img src="' . W_ROOT . '/images/tick.png" alt="Disabled" title="Disabled" border="0" /></a>';
        }
    }
    return $img;
}

function publishPro($tblName, $publish, $id, $phar_id) {
    if (is_array($id)) {
        $id = implode(",", $id);
    }

    //Statement to publish/unpublish the record
    $sql = "UPDATE $tblName
	SET status=$publish
	WHERE product_id IN ($id) AND pharmacy_id = $phar_id";
    return mysql_query($sql);
}

/*
  Function Publish/Unpublish a record in the table
 */

function publish($tblName, $publish, $id) {
    if (is_array($id)) {
        $id = implode(",", $id);
    }

    //Statement to publish/unpublish the record
    $sql = "UPDATE $tblName
	SET status=$publish
	WHERE id IN ($id)";
    return mysql_query($sql);
}

function publishAdvertise($tblName, $publish, $id) {
	if (is_array($id)) {
		$id = implode(",", $id);
	}

	//Statement to publish/unpublish the record
	$sql = "UPDATE $tblName
	SET adv_status=$publish
	WHERE adv_id IN ($id)";
	return mysql_query($sql);
}

function publishBanner($tblName, $publish, $id) {
	if (is_array($id)) {
		$id = implode(",", $id);
	}

	//Statement to publish/unpublish the record
	$sql = "UPDATE $tblName
	SET ban_status=$publish
	WHERE ban_id IN ($id)";
	return mysql_query($sql);
}

function idFormat($id, $lenght = 2) {
    $str_zero = "";
    $return_id = "$id";
    if (strlen($return_id) < $lenght) {
        for ($i = 1; $i <= ($lenght - strlen($return_id)); $i++) {
            $str_zero .= "0";
        }
    }
    $return_id = $str_zero . "$id";
    return $return_id;
}

function includefiles($arrfile) {
    foreach ($arrfile as $strfile) {
        $extension = substr($strfile, strrpos($strfile, '.') + 1, 2);
        if ($extension == "cs") {
            echo "<link rel=\"stylesheet\" href=\"" . W_ROOT . "/css/$strfile\" type=\"text/css\" />
			";
        } elseif ($extension == "js") {
            echo "<script language=\"JavaScript\" type=\"text/javascript\" src=\"" . W_ROOT . "/js/$strfile\"></script>
			";
        }
    }
}

//Function Load Editor When load_editor==true;
function load_editor() {
    echo "<script type=\"text/javascript\" src=\"" . W_ROOT . "/jscripts/tiny_mce/tiny_mce.js\"></script>";
    echo "<script type=\"text/javascript\" src=\"" . W_ROOT . "/jscripts/initialeditor.js\"></script>";
}

function alertmsg($str) {
    echo "<script language=\"javascript\">alert(\"$str\");</script>";
}

function redirect_to_parent($str) {
    echo "<script language=\"javascript\">window.parent.location.href=(\"$str\");</script>";
}

function load_iframe() {
    echo "<iframe scrolling=\"no\" id=\"fra\" name=\"fra\" frameborder=\"0\" height=\"1px\" width=\"1px\" style=\"display:none\"></iframe>";
}

function checkVar(&$var) {
    if (isset($var) and $var != '')
        return true;
    else
        return false;
}

function tep_session_name($name = '') {
    if (!empty($name)) {
        return session_name($name);
    } else {
        return session_name();
    }
}

function getAllGetParams($exclude_var_array = '') {
    if (!is_array($exclude_var_array))
        $exclude_var_array = array($exclude_var_array);

    $qString = array();

    foreach ($_GET as $key => $value) {
        if (trim($value) != '' && ($key != tep_session_name()) && ($key != 'error') && (!in_array($key, $exclude_var_array)) && ($key != 'x') && ($key != 'y')) {
            $qString[] = $key . '=' . rawurlencode(trim($value));
        }/* else {
          $qString[] = $key;
          } */
    }

    $qString = implode('&', $qString);

    return $qString;
}

/* * **********************************************************************
  Function delete record in the table
 * ********************************************************************** */

function deleteRecord($tblName, $condition = "") {
    //Statement to delete the record
    $sql = "DELETE FROM $tblName";
    if (!empty($condition))
        $sql .= " WHERE $condition";
    return mysql_query($sql);
}

function forError($text) {
    echo '<br />
			<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border:1px solid #FF0000; background:#F4C19F; height:50px; padding-left:10px;">
			<tr>
			<td width="3%">
			<img src="' . W_ROOT . '/images/notice-alert.png" width="29" height="29" border="0" alt="" align="left" /></td>
					<td width="96%">
					<span style="color:#FF0000; font-size:16px; font-weight:bold;">Error</span>&nbsp;&nbsp;' . $text . '
							</td>
							</tr>
							</table>';
}

function getPagingNav($sql, $pageNum, $rowsPerPage, $queryString = '') {
    $result = mysql_query($sql) or die('Error, query failed. ' . mysql_error());
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    $numrows = $row['numrows'];

    // how many pages we have when using paging?
    $maxPage = ceil($numrows / $rowsPerPage);

    $self = $_SERVER['PHP_SELF'];

    // creating 'previous' and 'next' link
    // plus 'first page' and 'last page' link
    // print 'previous' link only if we're not
    // on page one
    if ($pageNum > 1) {
        $page = $pageNum - 1;
        $prev = " <a href=\"$self?page=$page{$queryString}\">[Prev]</a> ";

        $first = " <a href=\"$self?page=1{$queryString}\">[First Page]</a> ";
    } else {
        $prev = ' [Prev] ';       // we're on page one, don't enable 'previous' link
        $first = ' [First Page] '; // nor 'first page' link
    }

    // print 'next' link only if we're not
    // on the last page
    if ($pageNum < $maxPage) {
        $page = $pageNum + 1;
        $next = " <a href=\"$self?page=$page{$queryString}\">[Next]</a> ";

        $last = " <a href=\"$self?page=$maxPage{$queryString}{$queryString}\">[Last Page]</a> ";
    } else {
        $next = ' [Next] ';      // we're on the last page, don't enable 'next' link
        $last = ' [Last Page] '; // nor 'last page' link
    }

    // return the page navigation link
    return $first . $prev . " Showing page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last;
}

function getPagingLink($sql, $itemPerPage = 10, $strGet = '', $page_link = '') {
    $result = mysql_query($sql);
    if (!empty($result)) {
        $pagingLink = '';
        $totalResults = dbNumRows($result);
        $totalPages = ceil($totalResults / $itemPerPage);

        // how many link pages to show
        $numLinks = 10;


        // create the paging links only if we have more than one page of results
        if ($totalPages > 1) {
            if (!empty($page_link)) {
                $self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?';
                //$self = $page_link . '&';
            } else {
                $self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?';
            }

            if (isset($_GET['page']) && (int) $_GET['page'] > 0) {
                $pageNumber = (int) $_GET['page'];
            } else {
                $pageNumber = 1;
            }

            // print 'previous' link only if we're not
            // on page one
            if ($pageNumber > 1) {
                $page = $pageNumber - 1;
                if ($page > 1) {
                    $prev = ' <a href="' . $self . 'page=' . $page . '&' . $strGet . '">&#171; Prev</a> ';
                } else {
                    $prev = '<a href="' . $self . '' . $strGet . '">&#171; Prev</a>';
                }

                $first = '<a href="' . $self . '' . $strGet . '">&#171; First</a>';
            } else {
                $prev = ''; // we're on page one, don't show 'previous' link
                $first = ''; // nor 'first page' link
            }

            // print 'next' link only if we're not
            // on the last page
            if ($pageNumber < $totalPages) {
                $page = $pageNumber + 1;
                $next = '<a href="' . $self . 'page=' . $page . '&' . $strGet . '">Next &#187;</a>';
                $last = '<a href="' . $self . 'page=' . $totalPages . '&' . $strGet . '">Last &#187;</a>';
            } else {
                $next = ''; // we're on the last page, don't show 'next' link
                $last = ''; // nor 'last page' link
            }

            $start = $pageNumber - ($pageNumber % $numLinks) + 1;
            $end = $start + $numLinks - 1;

            $end = min($totalPages, $end);

            $pagingLink = array();
            for ($page = $start; $page <= $end; $page++) {
                if ($page == $pageNumber) {
                    $pagingLink[] = "<b>$page</b>";   // no need to create a link to current page
                } else {
                    if ($page == 1) {
                        $pagingLink[] = '<a class="page larger" href="' . $self . '' . $strGet . '">' . $page . '</a>';
                    } else {
                        $pagingLink[] = '<a class="page larger" href="' . $self . 'page=' . $page . '&' . $strGet . '">' . $page . '</a>';
                    }
                }
            }

            $pagingLink = implode('', $pagingLink);

            // return the page navigation link
            $pagingLink = $first . $prev . $pagingLink . $next . $last;
        }

        return $pagingLink;
    }
}

function getPagingQuery($sql, $itemPerPage = 10) {

    if (isset($_GET['page']) && (int) $_GET['page'] > 0) {
        $page = (int) $_GET['page'];
    } else {
        $page = 1;
    }

    // start fetching from this row number
    $offset = ($page - 1) * $itemPerPage;
    return $sql . " LIMIT $offset, $itemPerPage";
}

function buildCategoryOptions($catId = 0) {
    $sql = "SELECT id, parent_id, category_name
			FROM tblcategory
			ORDER BY id";
    $result = mysql_query($sql) or die('Cannot get Product. ' . mysql_error());

    $categories = array();
    while ($row = dbFetchArray($result)) {
        list($id, $parentId, $name) = $row;

        if ($parentId == 0) {
            // we create a new array for each top level categories
            $categories[$id] = array('name' => $name, 'children' => array());
        } else {
            // the child categories are put int the parent category's array
            $categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
        }
    }

    // build combo box options
    $list = '';
    foreach ($categories as $key => $value) {
        $name = $key['name'];
        $children = $value['children'];

        //  $list .= "<optgroup label=\"$name\">";

        foreach ($children as $child) {
            $list .= "<option value=\"{$child['id']}\"";
            if ($child['id'] == $catId) {
                $list.= " selected";
            }

            $list .= ">{$child['name']}</option>\r\n";
        }

        //$list .= "</optgroup>";
    }

    return $list;
}

/*
  Make sure each key name in $requiredField exist
  in $_POST and the value is not empty
 */

function checkRequiredPost($requiredField) {
    $numRequired = count($requiredField);
    $keys = array_keys($_POST);

    $allFieldExist = true;
    for ($i = 0; $i < $numRequired && $allFieldExist; $i++) {
        if (!in_array($requiredField[$i], $keys) || $_POST[$requiredField[$i]] == '') {
            $allFieldExist = false;
        }
    }

    return $allFieldExist;
}

// show by category

class sub_class {

    function show_by_cate() {
        global $id;
        $sql = "SELECT t1.*, t1.top_view, t3.price, t3.pid, t2.images, t2.thumbnail FROM tblproduct AS t1
		INNER JOIN tblimage AS t2 ON t1.id=t2.product_id
		INNER JOIN tblproduct_in_pharmacy AS t3 ON t1.id=t3.product_id
		INNER JOIN tblproduct_in_category AS tcate ON tcate.product_id= t1.id
		INNER JOIN tblcategory AS tgory ON tgory.id=tcate.category_id
		WHERE tgory.parent_id=$id AND t3.`status`=1 ORDER BY t1.id DESC LIMIT 0,5";
        $result = mysql_query($sql);
        $i = 0;
        $border = "";
        while ($row = dbFetchAssoc($result)) {
            if ($i % 4 == 0 && $i > 0) {
                echo '';
                $border = "";
            } else if ($i % 4 > 0) {
                $border = '';
            }

            $url = W_ROOT;
            $article = $row['product_name'];
            global $char;
            $readmore = rm($article, $char);
            $imagedir = W_S_IMAGES_DIR;
            echo"<li class=\"s_by_cate\">
			<div class=\"thumb\"><a href=\"product/product_detail.php?product_id={$row['id']}\" title=\"{$row['product_name']}\"><img class=\"image_product_tap\" src=\"{$url}{$imagedir}{$row['thumbnail']}\" /></div>
			<div class=\"title\">{$readmore}</div></a>
			<span class=\"price\">{$row['price']} $</span>
			</li>";
        }
    }

}

// end show by category
// show by category

class by_category {

    function getCateid($parent) {
        $sql_1 = "SELECT id, parent_id FROM tblcategory WHERE parent_id = $parent";
        $result_1 = mysql_query($sql_1);
        $id = array();
        if (dbNumRows($result_1)) {
            while ($row_1 = mysql_fetch_assoc($result_1)) {
                $id[] = $row_1['id'];
            }
            $category = implode(',', $id);
        }
        if (!empty($category)) {
            $select = ("SELECT p.product_type, p.product_name, pic.product_id, pic.category_id, img.thumbnail,img.images, pip.price, pip.country_id,p.id,pip.pid
					FROM `tblproduct` AS p LEFT JOIN `tblimage` AS img ON p.id = img.product_id
					LEFT JOIN `tblproduct_in_pharmacy` AS pip ON p.id = pip.product_id
					LEFT JOIN tblproduct_in_category AS pic ON p.id = pic.product_id
					INNER JOIN tbl_color_size AS mix ON mix.pid=p.id
					WHERE pic.category_id IN ($category) AND pip.status = 1 GROUP BY p.id LIMIT 0,1");
            $result = mysql_query($select);
//            while ($row = mysql_fetch_assoc($result)) {
//                $url = W_ROOT;
//                $article = $row['product_name'];
//                $price = $row['price'];
//                global $char;
//                $readmore = rm($article, $char);
//                $imagedir = W_S_IMAGES_DIR;
//                echo"<div class=\"span3 product_block\"><div class=\"product-inner feature-inner\">
//				<div class=\"image\"><a href=\"product/?cat_p={$parent}\" title=\"{$row['product_name']}\"><img class=\"image_product_tap\" src=\"{$imagedir}{$row['images']}\" /></div>
//				<div class=\"wrap-infor\"><div class=\"name\"><a href=\"product/?cat_p={$parent}\" title=\"{$row['product_name']}\"></a>{$article}</div></div>
//				<div class=\"price\">$ {$price}</div></div></div>";
//            }
            return $result;
        }
    }

}

// end show by category
// Category
function category($id) {
    $g_name = mysql_query("SELECT * FROM tblcategory AS tgory
			WHERE tgory.id=$id");
    $g_name = mysql_fetch_assoc($g_name);
    echo $g_name['category_name'];
}

// end Category
// readmore
function rm($article, $char) {
    if (strlen($article) > $char) {
        return substr($article, 0, $char) . '...';
    } else
        return $article;
}

// end readmore

function com_by_user() {
    $com_get = array();
    global $last_word;
    $com_id = mysql_query("SELECT * FROM tblpharmacy WHERE shorturl='" . $last_word . "'");
    while ($com_get = mysql_fetch_assoc($com_id)) {
        $com_get;
    }
    return $com_get;
}

//company
class company {

    var $pharmacy_id;
    var $pharmacy_name;
    var $descriptions;
    var $address;
    var $phone;
    var $fax;
    var $email;
    var $website;
    var $open_hour;
    var $close_hour;
    var $license;
    var $pharmacy_image;
    var $user_id;
    var $province_id;
    var $cdate;
    var $mdate;
    var $status;
    var $shorturl;
    var $contact;
    var $views;

    function getcompany($last_word, $userId = "") {
        if ($userId == "") {

            $PastShortUrl = "shorturl='" . $last_word . "'";
        } else if ($userId) {
            $PastShortUrl = "user_id='" . $userId . "'";
        }
        $com_id = mysql_query("SELECT * FROM tblpharmacy WHERE $PastShortUrl");
        if (dbNumRows($com_id)) {
            $arr_array = mysql_fetch_assoc($com_id);
            extract($arr_array, EXTR_PREFIX_SAME, "");
            $this->pharmacy_id = $pharmacy_id;
            $this->pharmacy_name = $pharmacy_name;
            $this->descriptions = $descriptions;
            $this->address = $address;
            $this->phone = $phone;
            $this->fax = $fax;
            $this->email = $email;
            $this->website = $website;
            $this->open_hour = $open_hour;
            $this->close_hour = $close_hour;
            $this->license = $license;
            $this->pharmacy_image = $pharmacy_image;
            $this->user_id = $user_id;
            $this->province_id = $province_id;
            $this->cdate = $cdate;
            $this->mdate = $mdate;
            $this->status = $status;
            $this->shorturl = $shorturl;
            $this->contact = $contact;
            $this->views = $views;
        }
    }

}

//end company
// from user table
class user_account {

    var $fname;
    var $lname;
    var $username;
    var $title;
    var $address;
    var $phone;
    var $mobile;
    var $email;
    var $cdate;
    var $mdate;
    var $expire_date;
    var $user_type_id;
    var $account_type_id;
    var $country_id;
    var $last_visit;
    var $status;
    var $newsletter;
    var $session_id;
    var $secret;
    var $perm;
    var $online;
    var $account_type;
    var $activate;
    var $category;

    function getting_Id($getId) {
        $sql = "SELECT * FROM tbluser WHERE id = $getId";
        $result = mysql_query($sql);
        if (dbNumRows($result)) {
            $arr_array = mysql_fetch_assoc($result);
            extract($arr_array, EXTR_PREFIX_SAME, "");

            $this->fname = $first_name;
            $this->lname = $last_name;
            $this->username = $username;
            $this->title = $title;
            $this->address = $address;
            $this->phone = $phone;
            $this->mobile = $mobile;
            $this->email = $email;
            $this->cdate = $cdate;
            $this->mdate = $mdate;
            $this->expire_date = $expire_date;
            $this->user_type_id = $user_type_id;
            $this->account_type_id = $account_type_id;
            $this->country_id = $country_id;
            $this->last_visit = $last_visit;
            $this->status = $status;
            $this->newsletter = $newsletter;
            $this->session_id = $session_id;
            $this->secret = $secret_word;
            $this->perm = $perm;
            $this->online = $acc_online;
            $this->account_type = $account_type;
            $this->activate = $activate;
            $this->category = $cat_id;
        }
    }

}

//$account = new user_account();
//$account->getting_Id(160); for ID user
//echo $account->id;
//end
// get all from product table
class prodcut_tb {

    var $id;
    var $product_name;
    var $product_type;
    var $product_ordering;
    var $cdate;
    var $mdate;
    var $short_desciption;
    var $product_description;
    var $post_type;
    var $status;
    var $owner;
    var $top_sale;
    var $top_view;

    function getall_product($pro_id, $fromid = '') {
        if ($fromid == "") {
            $from_id = "id='" . $pro_id . "'";
        } else {
            $from_id = $fromid;
        }
        $pro_qu = mysql_query("SELECT * FROM tblproduct WHERE $from_id");
        if (dbNumRows($pro_qu)) {
            $arr_array = mysql_fetch_assoc($pro_qu);
            extract($arr_array, EXTR_PREFIX_SAME, "");
            $this->id = $id;
            $this->product_name = $product_name;
            $this->product_type = $product_type;
            $this->product_ordering = $product_ordering;
            $this->cdate = $cdate;
            $this->mdate = $mdate;
            $this->short_desciption = $short_desciption;
            $this->product_description = $product_description;
            $this->post_type = $post_type;
            $this->status = $status;
            $this->owner = $owner;
            $this->top_sale = $top_sale;
            $this->top_view = $top_view;
        }
    }

    function product_list($from_id) {
        $pro_qu_list = mysql_query("SELECT * FROM tblproduct WHERE $from_id");
        return $pro_qu_list;
    }

    //$product_detail = new prodcut_tb();
    //$GetProduct=$product_detail->product_detail($pro);
    //$Get_rows=mysql_fetch_assoc($GetProduct);
    //end product

    function product_detail($from_id) {
        $pro_detail = mysql_query("SELECT
				p.owner, p.id,pip.price,p.product_name,p.short_desciption,p.product_description,p.owner,img.thumbnail,images,original_img,pip.country_id,pip.pid
				FROM tblproduct p LEFT JOIN tblimage img ON  p.id=img.product_id
				LEFT JOIN tblproduct_in_pharmacy pip ON p.id = pip.product_id
				WHERE p.id=$from_id GROUP BY pip.product_id");
        return $pro_detail;
    }

}

//for email
class mailUser {

    function getmail($mailpath) {
        $email_n = mysql_query("SELECT * FROM contact WHERE $mailpath");
        return $email_n;
    }

}

//$mailpath   = "to_user='".$_SESSION['username']."'";
//$email      = new mailUser();
//$email      = $email->getmail($mailpath);
//$emailget   = mysql_fetch_assoc($email);
// end for email
//for check order
class chOder {

    function chOrder($orderfrom) {
        $ch_ord = mysql_query("SELECT * FROM tbl_order_item AS porderi
				INNER JOIN tbl_order AS porder ON porderi.od_id=porder.od_id
				INNER JOIN tblproduct_in_pharmacy AS pip ON pip.pid=porderi.pd_id
				WHERE pip.pharmacy_id = '" . $_SESSION['acc_id'] . "' AND porderi.delete_orderRow_status = 1 GROUP BY porder.od_id");

        return $ch_ord;
    }

}

//$orderfrom = "pro.owner='".$_SESSION['acc_id']."'";
// $check_order = new chOder();
//$check_ord      = mysql_num_rows($check_order->chOrder($orderfrom));
// end for check order
//for seller
class seller {

    function sellers($wseller) {
        $seller = mysql_query("SELECT * FROM tbl_style AS theme
				INNER JOIN tblpharmacy AS com ON theme.`by_company_id`=com.`user_id`
				WHERE $wseller");
        return $seller;
    }

}

//end for seller
//LABEL IN LIST STYLE for seller
function cat_by_s($parent_id, $level, $id) {
    $category_array = array();
    $sql3 = "SELECT category_id FROM tblproduct_in_category WHERE product_id = $id";
    $result3 = mysql_query($sql3);
    while ($row3 = mysql_fetch_assoc($result3)) {
        $category_array[] = $row3['category_id'];
    }
    //run our query. by default starts at top of
    //the tree (with zero depth)
    $result = mysql_query("SELECT * FROM tblcategory WHERE parent_id='" . $parent_id . "'");
    //display each child row
    $i = 0;
    while ($row = mysql_fetch_assoc($result)) {
        $i++;
        $checkedcat = (in_array($row['id'], $category_array)) ? ' checked="checked"' : '';
        echo '<tr>';
        echo '<td>' . $row['id'] . '</td>';
        echo '<td><input class="' . $i . '" ' . $checkedcat . ' type="checkbox" id="selectcat" name="selectcat[]" value="' . $row['id'] . '"/></td>';
        echo '<td>' . str_repeat('&#8212;&nbsp;', $level) . $row['category_name'] . "</td>\n";
        echo '</tr>';
        //we want to see all the children that belong to this
        //node? so we need to call *this* function again
        cat_by_s($row['id'], $level + 1, $id);
    }
    //echo '<ul class="categories">';
    //build_tree($parent_id=0,$level=0);
    //echo '</ul>';
}

//end LABEL IN LIST STYLE for seller
//remove ''""
function escape_query($escape) {
    return strtr($escape, array(
        "\0" => "",
        "'" => "&#39;",
        "\"" => "&#34;",
        "\\" => "&#92;",
        // more secure
        "<" => "&lt;",
        ">" => "&gt;",
    ));
}

//end remove ''""


/* get current menu by Socheat Ngann */
function get_current_cat($parent_id = 0, $level = 0, $current_id = '', $getSub = '') {
    $menu = '';
    $has_childs = false;
    //run our query. by default starts at top of
    //the tree (with zero depth)
    $result = mysql_query("SELECT * FROM tblcategory WHERE parent_id = $parent_id AND status = 1 ORDER BY ordering");
    //display each child row
    while ($row = mysql_fetch_assoc($result)) {
        if ($has_childs === false) {
            //don't print '<ul>' multiple times
            $has_childs = true;
            $menu .= '';
        } else {
            $menu .= '';
        }
        $Current = (($current_id == $row['id']) ? ' active' : '');
        $get_sub = (!empty($getSub) ? '&sub=' . $getSub : '');
        //indent as necessary and print name
        $menu .= '<li class="popular-category' . $Current . '" id="category-' . $level . '">';
        if ($current_id == $row['id']) {
            $menu .= '' . special_char($row['category_name']) . ' (' . count_prduct_in_cat($row['id']) . ')';
        } else {
            $menu .= '<a href="' . W_ROOT . '/product/?cat_id=' . (!empty($getSub) ? $getSub : $parent_id) . '&cat_p=' . $row['id'] . $get_sub . '">' . special_char($row['category_name']) . ' (' . count_prduct_in_cat($row['id']) . ')</a>';
        }
        if (!empty($getSub)) {
            //$menu .= get_current_cat($row['id'], $level + 1);
        }
        //$menu .= '</li>';
        if ($has_childs === false) {
            //don't print '<ul>' multiple times
            $has_childs = true;
            $menu .= '</li>';
        } else {
            $menu .= '</li>';
        }
        //we want to see all the children that belong to this
        //nodeï¿½ so we need to call *this* function again
    }
    return $menu;
}

/* count product in Categories by Socheat Ngann */

function count_prduct_in_cat($parent_id = 0) {
    if (!empty($parent_id)) {
        $result = select(Tblproductincat::TABLE, '', $where = array(Tblproductincat::category_id => $parent_id));
        $data = mysql_num_rows($result);
        $count_arr = array();
        /* check delete if not relate */
        if (!empty($data)) {
            while ($row = mysql_fetch_array($result)) {
                $pro_id = $row['product_id'];
                $cat_id = $row['category_id'];
                $ch_pro_count = select(Tblproduct::tblproduct, '', $where_p = array(Tblproduct::id => $pro_id, Tblproduct::status => 1));
                $data_count_arr = mysql_num_rows($ch_pro_count);
                if (!empty($data_count_arr)) {
                    array_push($count_arr, 1);
                }
                /* check */
                $ch_pro = select(Tblproduct::tblproduct, '', $where_p = array(Tblproduct::id => $pro_id));
                $data_ch = mysql_num_rows($ch_pro);
                if (empty($data_ch)) {
                    $del_cat = deleteRecord(Tblproductincat::TABLE, Tblproductincat::product_id . '=' . $pro_id . ' AND ' . Tblproductincat::category_id . '=' . $cat_id);
                }
            }
        }
        /* end check delete if not relate */
        $datas = count($count_arr);
        return $datas;
    } else {
        return FALSE;
    }
}

function generateWatermarkText($orginalFolder, $destinationFolder, $text = 'Psarinternet.com', $font) {

    // Watermark text color, Hex format. Must start from #
    $color = '#F9F9F9';

    // Font size
    $font_size = '24';

    // Angle for text rotation. For example 0 - horizontal, 90 - vertical
    $angle = 50;

    // Shadow? true or false
    $drop_shadow = true;

    // Shadow color, Hex format. Must start from #
    // This may help to make watermark text more distinguishable from image background
    $shadow_color = '#909009';

    // 1 - save as file on the server, 2 - output to browser, 3 - do both
    $mode = 1;

    #################################################################################
    #     END OF SETTINGS
    #################################################################################
    // Load functions for image watermarking
    if (!class_exists('WatermarkText')) {
        include("watermark_text.class.php");
    }

    // Watermark all the "jpg" files from images folder
    // and save watermarked images into destination folder
    $width = '';
    $height = '';
    $offset_x = '';
    $offset_y = '';
    foreach (glob($orginalFolder . '*.*') as $filename) {
        // Image path
        $imgpath = $filename;

        $imageInfo = getimagesize($filename);

        $width = $imageInfo[0];
        $height = $imageInfo[1];
        // Horizontal offset in pixels, from the right
        $offset_x = 0;

        // Vertical offset in pixels, from the bottom
        $offset_y = 0;
        // Where to save watermarked image
        $imgdestpath = $destinationFolder . basename($filename);

        // create class instance
        $img = new WatermarkText($imgpath);

        // shadow params
        $img->setShadow($drop_shadow, $shadow_color);

        // font params
        $img->setFont($font, $font_size);

        // Apply watermark
        $img->ApplyWatermark($text, $color, $angle, $offset_x, $offset_y);

        // Save on server
        $img->SaveAsFile($imgdestpath);

        // Output to browser
        //$img->Output();
        // release resources
        $img->Free();
    }
}

function generateWatermarkForEachImage($orginalFolder, $filename, $text = 'Psarinternet.com', $font) {
    if ('' != $filename) {
        // Watermark text color, Hex format. Must start from #
        $color = '#F9F9F9';

        // Font size
        $font_size = '24';

        // Angle for text rotation. For example 0 - horizontal, 90 - vertical
        $angle = 50;

        // Shadow? true or false
        $drop_shadow = true;

        // Shadow color, Hex format. Must start from #
        // This may help to make watermark text more distinguishable from image background
        $shadow_color = '#909009';

        // 1 - save as file on the server, 2 - output to browser, 3 - do both
        $mode = 1;

        #################################################################################
        #     END OF SETTINGS
        #################################################################################
        // Load functions for image watermarking
        if (!class_exists('WatermarkText')) {
            include("watermark_text.class.php");
        }

        // Watermark all the "jpg" files from images folder
        // and save watermarked images into destination folder
        $width = '';
        $height = '';
        $offset_x = '';
        $offset_y = '';
        $imgpath = $orginalFolder . $filename;
        if (file_exists($imgpath)) {
            $imageInfo = getimagesize($imgpath);
            $width = $imageInfo[0];
            $height = $imageInfo[1];
            // Horizontal offset in pixels, from the right
            $offset_x = 0;

            // Vertical offset in pixels, from the bottom
            $offset_y = 0;
            // Where to save watermarked image
            $imgdestpath = $orginalFolder . basename($filename);

            // create class instance
            $img = new WatermarkText($imgpath);

            // shadow params
            $img->setShadow($drop_shadow, $shadow_color);

            // font params
            $img->setFont($font, $font_size);

            // Apply watermark
            $img->ApplyWatermark($text, $color, $angle, $offset_x, $offset_y);

            // Save on server
            $img->SaveAsFile($imgdestpath);

            // Output to browser
            //$img->Output();
            // release resources
            $img->Free();
        }
    }
}

function generateWatermark($originalFolder, $destinationFolder, $filename, $watermarkPath) {
    // Load functions for image watermarking

    $imagePath = $originalFolder . $filename;
    $imageInfo = getimagesize($imagePath);

    // Horizontal offset in pixels, from the right
    $offset_x = $imageInfo[0] / 2;

    // Vertical offset in pixels, from the bottom
    $offset_y = $imageInfo[1] / 2;

    $quality = 50;

    // Where to save watermarked image
    $imgDestPath = $destinationFolder . basename($filename);

    // Watermark image
    $img = new Zubrag_watermark($imagePath);
    $img->ApplyWatermark($watermarkPath);
    $img->SaveAsFile($imgDestPath);
    $img->Free();
}

/* end get current menu */

/*
 * @general Funtion for insert
 * Usage: insert("TableName", $data = array("id" => "1","title" => "This my test","by"=>"Socheat");
 */

function insert($table, $data) {
    $keys = array();
    $values = array();
    foreach ($data as $key => $value) {
        $keys[] = $key;
        $values[] = $value;
    }
    $check = mysql_query("INSERT INTO $table (" . implode(',', $keys) . ") VALUES('" . implode("', '", $values) . "')");
    return mysql_insert_id();
}

/*
 * @general Funtion for Select
 * @usage: select("TableName", $field = array(test1,test2), $where= array(id=>1,name='Socheat'), $order='id ASC', $group = 'id', $limit =10, $offset = 1);
 */

function select($table, $field = array(), $where = array(), $order = 0, $group = 0, $limit = 0, $offset = 0) {
    if (!empty($field)) {
        $fields = implode(',', $field);
    } else {
        $fields = '*';
    }
    $sql = "SELECT $fields FROM " . $table;
    if (!empty($where)) {
        $len = count($where);
        $i = 0;
        foreach ($where as $key => $value) {
            if ($i == 0) {
                $sql .= ' WHERE ';
            }
            $sql .= $key . '=' . "'$value'";
            if ($i != $len - 1) {
                $sql .= ' AND ';
            }
            $i++;
        }
    }
    if (!empty($order)) {
        $sql .= ' ORDER BY ' . $order;
    }
    if (!empty($group)) {
        $sql .= ' GROUP BY ' . $group;
    }
    if (!empty($limit)) {
        $sql .= ' LIMIT ' . $limit;
    }
    if (!empty($offset)) {
        $sql .= ' OFFSET ' . $offset;
    }
    return mysql_query($sql);
}

/*
 * @general Funtion for Update
 * @create by Ngann Socheat
 * @usage: update("TableName", $SET = array(email=>'socheatnews@hotmail.com', 'id'=>10), $where= array(id=>1,name='Socheat'));
 */

function update($table, $SET = array(), $where = array()) {
    $sql = "UPDATE " . $table . ' SET ';
    if (!empty($SET)) {
        $lens = count($SET);
        $s = 0;
        foreach ($SET as $key => $value) {
            $sql .= $key . '=' . "'$value'";
            if ($s != $lens - 1) {
                $sql .= ', ';
            }
            $s++;
        }
    }
    if (!empty($where)) {
        $len = count($where);
        $i = 0;
        foreach ($where as $key => $value) {
            if ($i == 0) {
                $sql .= ' WHERE ';
            }
            $sql .= $key . '=' . "'$value'";
            if ($i != $len - 1) {
                $sql .= ' AND ';
            }
            $i++;
        }
    }
    return mysql_query($sql);
}

function GenPassword($passwordEnscript) {
    return hash("sha512", md5(sha1(md5($passwordEnscript))));
}

function user_reached_post() {
    date_default_timezone_set('Asia/Phnom_Penh');
    $sql = "SELECT *FROM tbluser AS u INNER JOIN tblpharmacy AS com ON u.`id` = com.`user_id` WHERE  u.id='" . $_SESSION['acc_id'] . "' AND com.`expire_date` IS NOT NULL";
    $sql_user_join_pharmacy = mysql_query($sql);
    $obj_user = mysql_fetch_object($sql_user_join_pharmacy);
    $pharmacy_id = !empty($obj_user->id) ? $obj_user->id : "";
    $email = !empty($obj_user->email) ? $obj_user->email : "";
    $LastName = !empty($obj_user->last_name) ? $obj_user->last_name : "";
    $Phone = !empty($obj_user->phone) ? $obj_user->phone : @$obj_user->mobile;
    $expire_date = !empty($obj_user->expire_date) ? $obj_user->expire_date : "";
    $current_date = strtotime("now");
    $days_5 = 86400 * 5;
    $near_5days_expire = $expire_date - $days_5;
    if ($near_5days_expire <= $current_date && $current_date < $expire_date) {
        send_mail_customer($email, $LastName, $Phone);
        product_limit_reach();
    } elseif ($current_date <= $expire_date) {

        product_limit_reach();
    } elseif ($current_date >= $expire_date) {

        $sql_expire_product = mysql_query("UPDATE tblproduct_in_pharmacy SET status=0 WHERE pharmacy_id='" . $pharmacy_id . "'");
    }
}

function cronJobProcessExpire() {
    date_default_timezone_set('Asia/Phnom_Penh');
    $sql_user_join_pharmacy = mysql_query("SELECT *FROM tbluser AS u INNER JOIN tblpharmacy AS com ON u.`id` = com.`user_id` WHERE com.`expire_date` IS NOT NULL");
    while ($obj_user = mysql_fetch_object($sql_user_join_pharmacy)) {
        $pharmacy_id = $obj_user->id;
        $email = $obj_user->email;
        $LastName = $obj_user->last_name;
        $Phone = !empty($obj_user->phone) ? $obj_user->phone : $obj_user->mobile;
        $expire_date = $obj_user->expire_date;
        $current_date = strtotime("now");
        $days_5 = 86400 * 5;
        $near_5days_expire = $expire_date - $days_5;
        if ($near_5days_expire <= $current_date && $current_date < $expire_date) {
            send_mail_customer($email, $LastName, $Phone);
            product_limit_reach();
        } elseif ($current_date <= $expire_date) {
            product_limit_reach();
        } elseif ($current_date >= $expire_date) {
            $sql_expire_product = mysql_query("UPDATE tblproduct_in_pharmacy SET status=0 WHERE pharmacy_id='" . $pharmacy_id . "'");
        }
    }
}

function product_limit_reach() {
    $com_id = $_SESSION['acc_id'];
    $sql = mysql_query("SELECT COUNT(pip.country_id) AS num_count FROM tblproduct AS p,tblproduct_in_pharmacy AS pip, tblproduct_in_category AS pic WHERE p.id = pip.product_id AND pip.pharmacy_id = $com_id GROUP BY pip.product_id ORDER BY pip.pid DESC");
    $countproducts = dbNumRows($sql);
    /* check user type */
    if ($_SESSION['usertype'] == 2) {
        $getAcountType = select(Tblusertype::TABLE, array(Tblusertype::price, Tblusertype::limit_product), array(Tblusertype::id => $_SESSION['acc_type']));
        $queryAcc = mysql_fetch_assoc($getAcountType);
        $ch_account_type = $queryAcc[Tblusertype::price];
        $ch_account_limit = $queryAcc[Tblusertype::limit_product];
    } else if ($_SESSION['usertype'] == 3) {
        $table_ref = Tblrefcode::tblname;
        $where_limit = array(
            Tblrefcode::name => 'free_account',
            Tblrefcode::type => 'global_setting',
        );
        $get_limit_id = select($table_ref, array(Tblrefcode::value), $where_limit);
        $row_limit_id = mysql_fetch_assoc($get_limit_id);
        $ch_account_limit = ((!empty($row_limit_id[Tblrefcode::value])) ? $row_limit_id[Tblrefcode::value] : '50');
    } else {
        $ch_account_limit = -1;
    }
    /* end check user type */
    if ($ch_account_limit == $countproducts) {
        /* send message for alert user and admin */
        alert_to_customer();
        /* end send message for alert user and admin */
        return TRUE;
    } else {
        return FALSE;
    }
}

function alert_to_customer() {
    $where_ch = array(
        Tblrefcode::oject_id => $_SESSION['acc_id'],
        Tblrefcode::type => 'send_message'
    );
    $check_field = select(Tblrefcode::tblname, array(Tblrefcode::value), $where_ch);
    $querySend = dbNumRows($check_field);
    if (!empty($querySend)) {
        $row_send = mysql_fetch_assoc($check_field);
        if ($row_send[Tblrefcode::value] == 1) {
            //send_mail_customer();
            /* check for ever sent or never send */
        }
    } else {
        $data_add = array(
            Tblrefcode::oject_id => $_SESSION['acc_id'],
            Tblrefcode::type => 'send_message',
            Tblrefcode::name => 'user_reached_products',
            Tblrefcode::value => 0,
        );
        $send_add = insert(Tblrefcode::tblname, $data_add);
        if ($send_add) {
            //send_mail_customer();
        }
    }
}

function send_mail_customer($email, $name, $phone) {
    include_once S_ROOT . '/libraryfiles/SendEmail.php';
    $get_config_user = select(Tblrefcode::tblname, array(Tblrefcode::value), array(Tblrefcode::name => 'mail_user_login', Tblrefcode::type => 'global_setting'));
    $row_config_user = mysql_fetch_assoc($get_config_user);
    $admin_email = $row_config_user[Tblrefcode::value];

    $transport = new SendEmail ();
    $name1 = $name;
    $subjects1 = $email;
    $header1 = $email;
    $BodyHeader1 = "Expire Account!";
    $BodyMessage1 = 'Dear ' . $name . ', <br/> Your account is nearly expired for 5 days, please contact to psarinternet to continue.';
    $transport1 = $transport->SendMail($name1, $email, $base = 0, $header1, $subjects1, $BodyHeader1, $BodyMessage1);

    /* start send email to admin */
    $transport = new SendEmail ();
    $name_admin = $name;
    $subjects_admin = $admin_email;
    $header_admin = $admin_email;
    $BodyHeader_admin = "Expire Account!";
    $BodyMessage_admin = 'Dear ' . $name . ', <br/> Your account nearly expire for 5 days <br/> Name : ' . $name . '<br/> Email: ' . $email . ' <br/> Phone :' . $phone;
    $transport1 = $transport->SendMail($name_admin, $admin_email, $base = 0, $header_admin, $subjects_admin, $BodyHeader_admin, $BodyMessage_admin);
    /* end send email to admin */
}

function replace_sp($values) {
    $normalizeChars = array(
        'ï¿½' => 'S',
        'ï¿½' => 's',
        'ï¿½' => 'Dj',
        'ï¿½' => 'Z',
        'ï¿½' => 'z',
        'ï¿½' => 'A',
        'ï¿½' => 'A',
        'ï¿½' => 'A',
        'ï¿½' => 'A',
        'ï¿½' => 'A',
        'ï¿½' => 'A',
        'ï¿½' => 'A',
        'ï¿½' => 'C',
        'ï¿½' => 'E',
        'ï¿½' => 'E',
        'ï¿½' => 'E',
        'ï¿½' => 'E',
        'ï¿½' => 'I',
        'ï¿½' => 'I',
        'ï¿½' => 'I',
        'ï¿½' => 'I',
        'ï¿½' => 'N',
        'ï¿½' => 'O',
        'ï¿½' => 'O',
        'ï¿½' => 'O',
        'ï¿½' => 'O',
        'ï¿½' => 'O',
        'ï¿½' => 'O',
        'ï¿½' => 'U',
        'ï¿½' => 'U',
        'ï¿½' => 'U',
        'ï¿½' => 'U',
        'ï¿½' => 'Y',
        'ï¿½' => 'B',
        'ï¿½' => 'Ss',
        'ï¿½' => 'a',
        'ï¿½' => 'a',
        'ï¿½' => 'a',
        'ï¿½' => 'a',
        'ï¿½' => 'a',
        'ï¿½' => 'a',
        'ï¿½' => 'a',
        'ï¿½' => 'c',
        'ï¿½' => 'e',
        'ï¿½' => 'e',
        'ï¿½' => 'e',
        'ï¿½' => 'e',
        'ï¿½' => 'i',
        'ï¿½' => 'i',
        'ï¿½' => 'i',
        'ï¿½' => 'i',
        'ï¿½' => 'o',
        'ï¿½' => 'n',
        'ï¿½' => 'o',
        'ï¿½' => 'o',
        'ï¿½' => 'o',
        'ï¿½' => 'o',
        'ï¿½' => 'o',
        'ï¿½' => 'o',
        'ï¿½' => 'u',
        'ï¿½' => 'u',
        'ï¿½' => 'u',
        'ï¿½' => 'y',
        'ï¿½' => 'y',
        'ï¿½' => 'b',
        'ï¿½' => 'y',
        'ï¿½' => 'f'
    );
    $getRF = strtr($values, $normalizeChars);
    return $getRF;
}

function normalize_str($str) {
    $invalid = array(
        'ï¿½' => '&Scaron;',
        'ï¿½' => '&scaron;',
        'ï¿½' => '&ETH;',
        'ï¿½' => '&#381;',
        'ï¿½' => '&#382;',
        'ï¿½' => '&Agrave;',
        'ï¿½' => '&Aacute;',
        'ï¿½' => '&Acirc;',
        'ï¿½' => '&Atilde;',
        'ï¿½' => '&Auml;',
        'ï¿½' => '&Aring;',
        'ï¿½' => '&AElig;',
        'ï¿½' => '&Ccedil;',
        'ï¿½' => '&Egrave;',
        'ï¿½' => '&Eacute;',
        'ï¿½' => '&Ecirc;',
        'ï¿½' => '&Euml;',
        'ï¿½' => '&Igrave;',
        'ï¿½' => '&Iacute;',
        'ï¿½' => '&Icirc;',
        'ï¿½' => '&Iuml;',
        'ï¿½' => '&Ntilde;',
        'ï¿½' => '&Ograve;',
        'ï¿½' => '&Oacute;',
        'ï¿½' => '&Ocirc;',
        'ï¿½' => '&Otilde;',
        'ï¿½' => '&Ouml;',
        'ï¿½' => '&Oslash;',
        'ï¿½' => '&Ugrave;',
        'ï¿½' => '&Uacute;',
        'ï¿½' => '&Ucirc;',
        'ï¿½' => '&Uuml;',
        'ï¿½' => '&Yacute;',
        'ï¿½' => '&THORN;',
        'ï¿½' => '&szlig;',
        'ï¿½' => '&agrave;',
        'ï¿½' => '&aacute;',
        'ï¿½' => '&acirc;',
        'ï¿½' => '&atilde;',
        'ï¿½' => '&auml;',
        'ï¿½' => '&aring;',
        'ï¿½' => '&aelig;',
        'ï¿½' => '&ccedil;',
        'ï¿½' => '&egrave;',
        'ï¿½' => '&eacute;',
        'ï¿½' => '&ecirc;',
        'ï¿½' => '&euml;',
        'ï¿½' => '&igrave;',
        'ï¿½' => '&iacute;',
        'ï¿½' => '&icirc;',
        'ï¿½' => '&iuml;',
        'ï¿½' => '&eth;',
        'ï¿½' => '&ntilde;',
        'ï¿½' => '&ograve;',
        'ï¿½' => '&oacute;',
        'ï¿½' => '&ocirc;',
        'ï¿½' => '&otilde;',
        'ï¿½' => '&ouml;',
        'ï¿½' => '&oslash;',
        'ï¿½' => '&ugrave;',
        'ï¿½' => '&uacute;',
        'ï¿½' => '&ucirc;',
        'ï¿½' => '&yacute;',
        'ï¿½' => '&yacute;',
        'ï¿½' => '&thorn;',
        'ï¿½' => '&yuml;',
        'ï¿½' => '&fnof;',
        "`" => "'",
        "ï¿½" => "'",
        "ï¿½" => ",",
        "`" => "'",
        "ï¿½" => "'",
        "ï¿½" => "\"",
        "ï¿½" => "\"",
        "ï¿½" => "'",
        "&acirc;ï¿½ï¿½" => "'",
        "{" => "",
        "~" => "",
        "ï¿½" => "-",
        "ï¿½" => "'",
        "ï¿½" => "&#176;",
        "ï¿½" => "&#176;",
    );

    $str = str_replace(array_keys($invalid), array_values($invalid), $str);

    return $str;
}

function special_char_upload($param) {
    $params = replace_sp(utf8_encode($param));
    $newphrase = str_replace(' ', '-', $params);
    $newphrases = str_replace(',', '', $newphrase);
    return $newphrases;
}

function special_char($param) {
    $param = normalize_str(utf8_encode(trim(html_entity_decode($param))));
    return $param;
}

function exist_domain($param) {
    $checkDomain = select(Tblcompany::tblcompany, $field = array(Tblcompany::shorturl), $where = array(Tblcompany::shorturl => $param));
    if (dbNumRows($checkDomain)) {
        $gen = genRandomString(4);
        $short = $param . $gen;
        return $short;
    } else {
        return $param;
    }
}

function genRandomString($length = 50) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters [rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

/* ---------------------------------------------- */
/* ------------ BEGIN PHP SNIPPET --------------- */
/* ------------- BY SOCHEAT NGANN ----------------- */
/* ---------------------------------------------- */

// $this_cat_id: the current category id number
// $flarn: just a counter, call it as 0 in your
// function call and forget about it
// $keep_cat_id: the cat id number again - so that
// it can decide whether to make a
// category a link at the top while you're in the
// "product" page
function get_crumbs($this_cat_id, $flarn, $keep_cat_id) {
    $link_to_page = $_SERVER['PHP_SELF'];
    if (!isset($this_cat_id)) {
// if we are already "home", dont make home a link
        $this_cat_id = "0";
        echo "Home << ";
    }
// get the info and parent id for whatever category
// weâ€™re currently in
    $sql = "SELECT id, parent_id,category_name FROM tblcategory ";
    $sql .="where id = $this_cat_id";
    $show_crumb_trail = mysql_query($sql);
    $num_crumbs = mysql_num_rows($show_crumb_trail);
// if we actually have some resultsâ€¦.
    if ($num_crumbs > 0) {
        list($cat_id, $cat_parent, $cat_name) = mysql_fetch_row($show_crumb_trail);
        $cat_id_array[$flarn] = $cat_id;
        $cat_parent_id_array[$flarn] = $cat_parent;
        $cat_name_array[$flarn] = $cat_name;
        if ($cat_id_array[$flarn] > 0) {
            mysql_free_result($show_crumb_trail);
// increment $next by one
            $next = $flarn + 1;
            if ($flarn == 0) {
                //echo "Home << ";
            }
// now lets call the function again to loop through
// the other categories
// until weâ€™re left with none
            get_crumbs($cat_parent_id_array[$flarn], $next, $keep_cat_id);
// Since $keep_cat_id is the id number of original
// category weâ€™re in,
// now we check to see whether or not we have to
// make the real category
// name a link or not
// (If weâ€™re looking at the main category display,
// we wouldnâ€™t have to,
// since weâ€™re already *in* the category.Ã‚ Ã‚ This is
// more useful for when you have a product
// display page, that way the link back to the
// category that item orÃ‚ Ã‚ product lives in
// will be created
            switch ($next) {
                case 1:
                    $nums = 5;
                    $z_index = 95;
                    break;
                case 2:
                    $nums = 4;
                    $z_index = 96;
                    break;
                case 3:
                    $nums = 3;
                    $z_index = 97;
                    break;
                case 4:
                    $nums = 2;
                    $z_index = 98;
                    break;
            }
            if ($keep_cat_id == $cat_id_array[$flarn]) {
                //echo $cat_name_array[$flarn];
                echo '<a class="lever_' . $nums . '" style="z-index:' . $z_index . '" href="' . base_url . 'product?cat_id=' . $cat_id_array[$flarn] . '">' . special_char($cat_name_array[$flarn]) . '</a>';
            } else {
                //echo "$cat_name_array[$flarn] >> ";
                echo '<a class="lever_' . $nums . '" style="z-index:' . $z_index . '" href="' . base_url . 'product?cat_id=' . $cat_id_array[$flarn] . '">' . special_char($cat_name_array[$flarn]) . '</a>';
            }
        }
    }
}

function getmeta_tag($param = '', $pro_id = '', $home = '') {
    /* for home page */
    if (!empty($home)) {
        if ($param == 'keyword') {
            $where_key = array(
                Tblrefcode::name => 'meta_tage_keyword',
                Tblrefcode::type => 'global_setting',
            );
        } else if ($param == 'description') {
            $where_key = array(
                Tblrefcode::name => 'meta_tage_description',
                Tblrefcode::type => 'global_setting',
            );
        }
        $get_data = select(Tblrefcode::tblname, array(Tblrefcode::value), $where_key);
        $row_data = mysql_fetch_assoc($get_data);
        $data_meta = $row_data[Tblrefcode::value];
    } else {
        /* for product detail */

        if ($param == 'keyword') {
            $field = array(Tblproduct::keyword);
            $where_key = array(
                Tblproduct::id => $pro_id
            );
            $get_data = select(Tblproduct::tblproduct, $field, $where_key);
            $row_data = mysql_fetch_assoc($get_data);
            $data_meta = $row_data[Tblproduct::keyword];
        } else if ($param == 'description') {
            $field = array(Tblproduct::desc_seo);
            $where_key = array(
                Tblproduct::id => $pro_id
            );
            $get_data = select(Tblproduct::tblproduct, $field, $where_key);
            $row_data = mysql_fetch_assoc($get_data);
            $data_meta = $row_data[Tblproduct::desc_seo];
        }
    }
    return $data_meta;
}

function replaceString($values) {
    $normalizeChars = array(
        'Å ' => 'S',
        'Å¡' => 's',
        'Ã�' => 'Dj',
        'Å½' => 'Z',
        'Å¾' => 'z',
        'Ã€' => 'A',
        'Ã�' => 'A',
        'Ã‚' => 'A',
        'Ãƒ' => 'A',
        'Ã„' => 'A',
        'Ã…' => 'A',
        'Ã†' => 'A',
        'Ã‡' => 'C',
        'Ãˆ' => 'E',
        'Ã‰' => 'E',
        'ÃŠ' => 'E',
        'Ã‹' => 'E',
        'ÃŒ' => 'I',
        'Ã�' => 'I',
        'ÃŽ' => 'I',
        'Ã�' => 'I',
        'Ã‘' => 'N',
        'Ã’' => 'O',
        'Ã“' => 'O',
        'Ã”' => 'O',
        'Ã•' => 'O',
        'Ã–' => 'O',
        'Ã˜' => 'O',
        'Ã™' => 'U',
        'Ãš' => 'U',
        'Ã›' => 'U',
        'Ãœ' => 'U',
        'Ã�' => 'Y',
        'Ãž' => 'B',
        'ÃŸ' => 'Ss',
        'Ã ' => 'a',
        'Ã¡' => 'a',
        'Ã¢' => 'a',
        'Ã£' => 'a',
        'Ã¤' => 'a',
        'Ã¥' => 'a',
        'Ã¦' => 'a',
        'Ã§' => 'c',
        'Ã¨' => 'e',
        'Ã©' => 'e',
        'Ãª' => 'e',
        'Ã«' => 'e',
        'Ã¬' => 'i',
        'Ã­' => 'i',
        'Ã®' => 'i',
        'Ã¯' => 'i',
        'Ã°' => 'o',
        'Ã±' => 'n',
        'Ã²' => 'o',
        'Ã³' => 'o',
        'Ã´' => 'o',
        'Ãµ' => 'o',
        'Ã¶' => 'o',
        'Ã¸' => 'o',
        'Ã¹' => 'u',
        'Ãº' => 'u',
        'Ã»' => 'u',
        'Ã½' => 'y',
        'Ã½' => 'y',
        'Ã¾' => 'b',
        'Ã¿' => 'y',
        'Æ’' => 'f',
        '~' => 'k',
        '!' => 's',
        '@' => 'i',
        '#' => 'o',
        '$' => 'p',
        '%' => 'r',
        '&' => 'r',
        '*' => 'u',
        '^' => 'e'
    );
    $getRF = strtr($values, $normalizeChars);
    return $getRF;
}

function Special_String_Upload($param) {

    $params = replaceString($param);
    $newphrase = str_replace(' ', '-', $params);
    $newphrases = str_replace(',', '', $newphrase);
    return $newphrases;
}
function showProduct($data, $myprice, $cat_id='') {
    if (!empty($cat_id)) {
        $by_cat = '&cat_id=' . $cat_id;
    } else {
        $by_cat = '';
    }
    $char = 42;
    $title = $data['product_name'];
    $title_limit = rm($title, $char);
    $list = '<div class="product-inner feature-inner">';
    $list .= '<div class="image">';
    $list .= '<a href="' . base_url . 'product/product_detail.php?product_id=' . $data['id'] . $by_cat . '" title="' . $data['product_name'] . '">';
    $list .= '<img src="' . W_S_IMAGES_DIR_THUMB . $data['images'] . '" />';
    $list .= '</a>';
    $list .= '</div>';
    $list .= '<div class="wrap-infor"><div class="name">';
    $list .= '<a href="' . base_url . 'product/product_detail.php?product_id=' . $data['id'] . $by_cat . '" title="' . $data['product_name'] . '">' . $title_limit . '</a>';
    $list .= '</div></div>';
    $list .= '<div class="price">Price:<span class="price-new">$' . $myprice['price'] . '</span></div>';
    $list .= '</div>';
    return $list;
}
include(S_ROOT . '/languages/common.php');

